import React, {Component } from 'react';
import CounterStore from './CounterStore'
import * as Actions from './Actions'

class CounterView extends Component {
    constructor(props){
        super(props);
        this.onChange = this.onChange.bind(this);
        this.onClickIncrementButton = this.onClickIncrementButton.bind(this);
        this.onClickDecrementButton = this.onClickDecrementButton.bind(this);

        this.state = {count:CounterStore.getCounterValues()[this.props.caption]};
    }

    componentDidMount(){
        CounterStore.addChangeListener(this.onChange);
    }

    componentWillUnmount(){
        CounterStore.removeChangeListener(this.onChange);
    }

    onChange(){
        const newCount = CounterStore.getCounterValues()[this.props.caption];
        this.setState({count:newCount});
    }

    onClickIncrementButton(){
        Actions.increment(this.props.caption);
    }

    onClickDecrementButton(){
        Actions.decrement(this.props.caption);
    }

    render(){
        const {caption} = this.props;
        return (
            <div style={{margin:50}}>
                <button onClick={this.onClickIncrementButton}>+</button>
                <span style={{backgroundColor:'#999999',color:'#FF0000',marginLeft:50,marginRight:50}}>{caption} count:{this.state.count}</span>
                <button onClick={this.onClickDecrementButton}>-</button>
            </div>
        );
    }
}

export default CounterView;